
(function(){
//用户收藏
var role = require("./role");
var BusCon = require("../../core/bus/_con");
var UserCon = require("../../core/user/_con");
var GoodsCon = require("../../core/goods/_con");
var AchCon = require("../../core/ach/_con");
var db = require("../../core/db/index");
var config = require("../../core/_include/config");
var ResponObj = require("../_include/ResponObj");

module.exports = {
	prefix:"/user/collect",
	get:{
		//获取已经登陆的用户的收藏商品的ID数组
		//.params.num 返回的最大数量||5
		"/":function *(){
			try{
				var user  = role.getUser(this);
			}catch(errorMsg){
				this.body = ResponObj("error",errorMsg);
				return;
			}
			var num = (+this.params.num)||5;
			var collectGoods = user.getCollect(num);
			this.body = ResponObj("json",collectGoods);
		},
		"/detail":function *() {
			try{
				var user  = role.getUser(this);
			}catch(errorMsg){
				this.body = ResponObj("error",errorMsg);
				return;
			}
			var num = (+this.params.num)||5;
			var collectGoods = user.getCollect(num);
			collectGoods.forEach(function(goods_id,index){
				collectGoods[index] = GoodsCon.get(goods_id);
			});
			this.body = ResponObj("json",collectGoods);
		},
		"/remove/:goods_id":function * () {
			try{
				var user  = role.getUser(this);
			}catch(errorMsg){
				this.body = ResponObj("error",errorMsg);
				return;
			}
			var goods_id = this.params.goods_id;
			if(user.removeGoodsFromCollect(goods_id)){
				this.body = ResponObj("json","已成功取消收藏");
			}else{
				this.body = ResponObj("error","找不到指定商品");
			}
		}
	},
	post:{
		//添加商品编号到购物车
		"/":function *(){
			try{
				var user  = role.getUser(this);
			}catch(errorMsg){
				this.body = ResponObj("error",errorMsg);
				return;
			}
			var goods_id = this.request.body.goods_id;
			if (GoodsCon.get(goods_id)) {
				if(user.addGoodsToCollect(goods_id)){
					this.body = ResponObj("json","成功收藏商品")
				}else{
					this.body = ResponObj("error","已收藏过此商品")
				}
			}else{
				this.body = ResponObj("error","找不到指定商品")
			}
		},
	},
	"delete":{
		"/":function *(){
			try{
				var user  = role.getUser(this);
			}catch(errorMsg){
				this.body = ResponObj("error",errorMsg);
				return;
			}
			var goods_id = this.request.body.goods_id;
			if(user.removeGoodsFromCollect(goods_id)){
				this.body = ResponObj("json","已成功取消收藏");
			}else{
				this.body = ResponObj("error","找不到指定商品");
			}
		}
	}
}
}());